package com.oig.sys.oauth.handler;

import com.oig.common.constants.CommonConstants;
import com.oig.common.module.SysResponse;
import com.oig.common.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
public class AuthenticationExceptionEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        log.error("authentication exception..", authException);
        response.setCharacterEncoding(CommonConstants.UTF8);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        PrintWriter printWriter = response.getWriter();
        SysResponse<String> sysResponse = SysResponse.failed();
        if (authException != null) {
            sysResponse.setMsg("认证失败，请检查用户名密码！");
            sysResponse.setData(authException.getMessage());
        }
        printWriter.write(JsonUtil.toJSONString(sysResponse));
        printWriter.flush();
        printWriter.close();
    }


}
